<template>
	<view class="container">
		<!-- 状态栏（绿色） -->
		<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
		
		<!-- 自定义导航栏（绿色背景） -->
		<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content">
				<!-- 左侧返回箭头 -->
				<view class="navbar-left" @click="handleBack">
					<uni-icons type="left" size="20" color="#FFFFFF"></uni-icons>
				</view>
				<!-- 中间标题 -->
				<view class="navbar-title">导出数据</view>
			</view>
		</view>

		<!-- 主内容区 -->
		<view class="main-content" :style="{ marginTop: (statusBarHeight + 44) + 'px' }">
			<!-- 加载遮罩层 -->
			<view class="loading-mask" v-if="isExporting">
				<view class="loading-container">
					<view class="loading-spinner"></view>
					<text class="loading-text">正在导出中...</text>
				</view>
			</view>

			<!-- 密码输入模态框 -->
			<password-input-modal 
				:visible="showPasswordModal" 
				@close="handleClosePasswordModal"
				@confirm="handlePasswordConfirm"
			></password-input-modal>

			<!-- 选项列表 -->
			<view class="options-list">
				<!-- 导出加密备份文件 -->
				<view class="option-item" @click="handleExportEncrypted">
					<view class="option-info">
						<text class="option-title">导出加密备份文件 (推荐)</text>
						<text class="option-desc">数据已加密! 日常备份请用这个!</text>
					</view>
					<uni-icons type="right" size="14" color="#CCCCCC"></uni-icons>
				</view>

				<!-- 导出 JSON 格式数据 -->
				<view class="option-item" @click="handleExportJSON">
					<view class="option-info">
						<text class="option-title">导出 JSON 格式数据</text>
						<text class="option-desc">数据未加密! 请勿发送给他人!</text>
					</view>
					<uni-icons type="right" size="14" color="#CCCCCC"></uni-icons>
				</view>

				<!-- 导出 TEXT 格式数据 -->
				<view class="option-item" @click="handleExportTEXT">
					<view class="option-info">
						<text class="option-title">导出 TEXT 格式数据</text>
						<text class="option-desc">数据未加密! 请勿发送给他人!</text>
					</view>
					<uni-icons type="right" size="14" color="#CCCCCC"></uni-icons>
				</view>
			</view>

			<!-- 底部指示器 -->
			<view class="home-indicator-wrapper">
				<view class="home-indicator"></view>
			</view>
		</view>
	</view>
</template>

<script>
	import { exportJSONData, exportTEXTData, exportEncryptedBackup } from '@/utils/importExport/index.js';
	import PasswordInputModal from '@/components/Modal/password-input-modal.vue';

	export default {
		components: {
			PasswordInputModal
		},
		data() {
			return {
				statusBarHeight: 0,
				isExporting: false,
				showPasswordModal: false
			}
		},
		onLoad() {
			// 获取状态栏高度
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight || 20;
		},
		methods: {
			handleBack() {
				uni.navigateBack();
			},
			handleExportEncrypted() {
				// 显示密码输入模态框
				this.showPasswordModal = true;
			},
			handleClosePasswordModal() {
				this.showPasswordModal = false;
			},
			async handlePasswordConfirm(password) {
				this.showPasswordModal = false;
				
				// 开始导出
				try {
					this.isExporting = true;
					
					// 使用 nextTick 确保 UI 更新
					await this.$nextTick();
					
					// 异步执行加密导出操作
					const exportResult = await new Promise((resolve, reject) => {
						setTimeout(async () => {
							try {
								const result = await exportEncryptedBackup(password);
								resolve(result);
							} catch (error) {
								reject(error);
							}
						}, 200);
					});
					
					// 保存文件
					await this.saveFile(exportResult.data, exportResult.filename, 'application/octet-stream');
				} catch (error) {
					console.error('导出失败:', error);
					// uni.showToast({
					// 	title: error.message || '导出失败',
					// 	icon: 'none',
					// 	duration: 2000
					// });
				} finally {
					this.isExporting = false;
				}
			},
			async handleExportJSON() {
				try {
					this.isExporting = true;
					
					// 使用 nextTick 确保 UI 更新
					await this.$nextTick();
					
					// 异步执行导出操作，确保加载动画显示
					const exportResult = await new Promise((resolve, reject) => {
						setTimeout(() => {
							try {
								const result = exportJSONData();
								resolve(result);
							} catch (error) {
								reject(error);
							}
						}, 200);
					});
					
					// 保存文件
					await this.saveFile(exportResult.data, exportResult.filename, exportResult.mimeType);
				} catch (error) {
					console.error('导出失败:', error);
					// uni.showToast({
					// 	title: error.message || '导出失败',
					// 	icon: 'none',
					// 	duration: 2000
					// });
				} finally {
					this.isExporting = false;
				}
			},
			async handleExportTEXT() {
				try {
					this.isExporting = true;
					
					// 使用 nextTick 确保 UI 更新
					await this.$nextTick();
					
					// 异步执行导出操作，确保加载动画显示
					const exportResult = await new Promise((resolve, reject) => {
						setTimeout(() => {
							try {
								const result = exportTEXTData();
								resolve(result);
							} catch (error) {
								reject(error);
							}
						}, 200);
					});
					
					// 保存文件
					await this.saveFile(exportResult.data, exportResult.filename, exportResult.mimeType);
				} catch (error) {
					console.error('导出失败:', error);
					// uni.showToast({
					// 	title: error.message || '导出失败',
					// 	icon: 'none',
					// 	duration: 2000
					// });
				} finally {
					this.isExporting = false;
				}
			},
			saveFile(data, filename, mimeType) {
				return new Promise((resolve, reject) => {
					// #ifdef H5
					// H5 平台：创建下载链接
					try {
						const blob = new Blob([data], { type: mimeType });
						const url = URL.createObjectURL(blob);
						const link = document.createElement('a');
						link.href = url;
						link.download = filename;
						document.body.appendChild(link);
						link.click();
						document.body.removeChild(link);
					URL.revokeObjectURL(url);
					// uni.showToast({
					// 	title: '导出成功',
					// 	icon: 'success',
					// 	duration: 1500
					// });
					resolve();
					} catch (error) {
						reject(error);
					}
					// #endif
					
					// #ifdef APP-PLUS
					// APP 平台：保存到文件系统
					{
						const fs = uni.getFileSystemManager();
						const filePath = `${uni.env.USER_DATA_PATH}/${filename}`;
						fs.writeFile({
							filePath: filePath,
							data: data,
							success: () => {
								// uni.showToast({
								// 	title: '导出成功',
								// 	icon: 'success',
								// 	duration: 1500
								// });
								resolve();
								// 可以打开文件管理器或分享
								// plus.share.sendWithSystem({
								// 	content: filePath,
								// 	type: 'file'
								// });
							},
							fail: (err) => {
								console.error('保存文件失败:', err);
								// uni.showToast({
								// 	title: '保存文件失败',
								// 	icon: 'none'
								// });
								reject(err);
							}
						});
					}
					// #endif
					
					// #ifdef MP
					// 小程序平台：使用文件系统
					{
						const fs = uni.getFileSystemManager();
						const filePath = `${uni.env.USER_DATA_PATH}/${filename}`;
						fs.writeFile({
							filePath: filePath,
							data: data,
							success: () => {
								// uni.showToast({
								// 	title: '导出成功',
								// 	icon: 'success',
								// 	duration: 1500
								// });
								resolve();
							},
							fail: (err) => {
								console.error('保存文件失败:', err);
								// uni.showToast({
								// 	title: '保存文件失败',
								// 	icon: 'none'
								// });
								reject(err);
							}
						});
					}
					// #endif
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		width: 100%;
		height: 100vh;
		background-color: #FFFFFF;
		display: flex;
		flex-direction: column;
	}

	// 状态栏（绿色）
	.status-bar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		background-color: #008D57;
		z-index: 1001;
		width: 100%;
	}

	// 自定义导航栏（绿色背景）
	.custom-navbar {
		background-color: #008D57;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 1000;
		width: 100%;
	}

	.navbar-content {
		height: 44px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
		color: #FFFFFF;
		position: relative;
	}

	.navbar-left {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 40rpx;
		height: 40rpx;
		flex-shrink: 0;
	}

	.navbar-title {
		font-size: 34rpx;
		font-weight: 500;
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		letter-spacing: 0.5rpx;
	}

	// 主内容区
	.main-content {
		flex: 1;
		width: 100%;
		background-color: #FFFFFF;
		display: flex;
		flex-direction: column;
		padding-bottom: 40rpx;
	}

	.options-list {
		flex: 1;
		padding: 32rpx;
	}

	.option-item {
		display: flex;
		align-items: center;
		padding: 32rpx;
		background-color: #F5F5F5;
		border-radius: 16rpx;
		margin-bottom: 24rpx;
		cursor: pointer;
		transition: opacity 0.2s;
		
		&:active {
			opacity: 0.7;
		}
	}

	.option-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 12rpx;
	}

	.option-title {
		font-size: 30rpx;
		color: #333333;
		font-weight: 400;
		line-height: 1.2;
	}

	.option-desc {
		font-size: 24rpx;
		color: #999999;
		font-weight: 400;
		line-height: 1.2;
	}

	.home-indicator-wrapper {
		padding: 20rpx 0;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.home-indicator {
		width: 80rpx;
		height: 4rpx;
		background-color: #CCCCCC;
		border-radius: 2rpx;
	}

	// 加载遮罩层
	.loading-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 9999;
	}

	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: #FFFFFF;
		border-radius: 16rpx;
		padding: 60rpx 80rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
	}

	.loading-spinner {
		width: 60rpx;
		height: 60rpx;
		border: 4rpx solid #F0F0F0;
		border-top-color: #008D57;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 32rpx;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}
		100% {
			transform: rotate(360deg);
		}
	}

	.loading-text {
		font-size: 28rpx;
		color: #333333;
		font-weight: 400;
	}
</style>

